package krow.dev.contest.controller;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import krow.dev.contest.model.ContestItem;
import krow.dev.contest.model.MyProgressDialog;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;

public class RssReader extends AsyncTask<Void, Void, Boolean> {

	
	
	private Pattern sTitlePattern = Pattern.compile("^(?:\\[([^\\[\\]]+)\\](.+))");
	
	private Context mContext;
	
	private List<ContestItem> mContestItemList;
	
	private MyProgressDialog mLoadDialog;
	
	private OnCompletionListener mCompletionListener;
	
	private String mUrl;
	
	private int mCount;
	
	private boolean mIsCancelled;
	
	
	public RssReader(Context context) {

		mContext = context;
		
		mContestItemList = new ArrayList<ContestItem>();
	}

	public void setCompletionListener(OnCompletionListener completionListener) {

		mCompletionListener = completionListener;
	}
	
	public int getContestSize() {
		return mCount;
	}
	
	public void setDetailcategoryItemURL(String url) {
		
		mUrl = url;
	}

	public void cancel() {

		mIsCancelled = true;
	}

	@Override
	protected void onPreExecute() {

		mLoadDialog = MyProgressDialog.show(mContext, "업데이트 중..", null, true, true, new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub

				mLoadDialog.dismiss();
			}
		});
	}

	@Override
	protected Boolean doInBackground(Void... params) {

		return request(mUrl);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (mLoadDialog != null) {
			mLoadDialog.dismiss();
			
		}

		if (result && !mIsCancelled) {
			if (mCompletionListener != null) {
				mCompletionListener.onCompletion(mContestItemList);
			}
		}
	}

	private boolean request(String url) {

		boolean isSucceed = true;

		try {
			
			URL requestUrl = new URL(url);
			
			HttpURLConnection httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
			if (httpURLConnection == null) {
				return false;
			}
			
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setUseCaches(false);
			

			if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				parseByDomParser(httpURLConnection.getInputStream());
			}

			httpURLConnection.disconnect();
		} catch (Exception e) {
			
			isSucceed = false;
		}
		
		return isSucceed;
	}
	
	private void parseByDomParser(InputStream inputStream) throws Exception {

		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		Document document = documentBuilder.parse(inputStream);

		Element element = document.getDocumentElement();
		NodeList nodeList = element.getElementsByTagName("item");

		mCount = nodeList.getLength();
		for (int i = 0; i < mCount; i++) {
			Element itemElement = (Element) nodeList.item(i);
			Element titleElement = (Element) itemElement.getElementsByTagName("title").item(0);
			Element linkElement = (Element) itemElement.getElementsByTagName("link").item(0);
			Element descriptionElement = (Element) itemElement.getElementsByTagName("description").item(0);
			Element creatorElement = (Element) itemElement.getElementsByTagName("dc:creator").item(0);
			Element dateElement = (Element) itemElement.getElementsByTagName("pubDate").item(0);

			String subject = titleElement.getTextContent();
			String title = subject;
			String department = null;
			String test = null;

			try {
				Matcher matcher = sTitlePattern.matcher(subject);
				if(matcher.find()){
					department = matcher.group(1);
					title = matcher.group(2);
				}
			} catch (Exception e) {

			}
			Log.e("test", "title: " + title);
			Log.e("test", "department: " + department);
			
			
			
			ContestItem contestItem = new ContestItem();
			contestItem.setTitle(title);
			contestItem.setDepartment(department);
			contestItem.setDescription(descriptionElement.getTextContent()); 
			contestItem.setLink(linkElement.getTextContent());
			contestItem.setCreator(creatorElement.getTextContent());

			mContestItemList.add(contestItem);
		}
	}

	/*
	private int parseByPullParser(InputStream inputStream){
		
		int count = 0;
		
		try {
			XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance();
			XmlPullParser xmlPullParser = xmlPullParserFactory.newPullParser();
			xmlPullParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
			xmlPullParser.setInput(inputStream, "euc-kr");
			
			int event = xmlPullParser.getEventType();
			while (event != XmlPullParser.END_DOCUMENT) {
				
				String elementName = xmlPullParser.getName();
				
				switch (event) {
				case XmlPullParser.END_TAG:
					if(elementName.equals("item")){
						count++;
					}
					break;
				}
				
				event = xmlPullParser.next();
			}
		} catch (Exception e) {

		}
		
		return count;
	}
	*/
	
	public interface OnCompletionListener {

		public abstract void onCompletion(List<ContestItem> detailcategoryItems);
	}
}